#include "header.h"
#include "macros.h"
#include "types.h"
#include "db.h"

MYSQL *mysql_con = NULL;

/*#### STUBS ####*/
int db_create (void){
	return 0;
}

int db_export (void){
	return 0;
}

int db_import (const char* path){
	return 0;
}
/*#### STUBS ####*/

int db_update_cash (Client* me, unsigned long newcash){

 int err;

	err = db_query (FORMAT_DB_UPDATE_CASH, newcash, me->user);
		if (err < 0){
			return -1;
		}

 return 0;
}

int db_auth (Client* me, char user[USERSIZE], char pass[PASSSIZE]){

 int err;
 my_ulonglong nr;
 MYSQL_RES* mres = NULL;
 MYSQL_ROW sqlrow;

	err = db_query (FORMAT_DB_AUTH_USER, user, pass);
		if (err < 0){
			return -1;
		}

	mres = mysql_store_result (mysql_con);
		if (mres == NULL){
			db_err ();
			return -1;
		}

	nr = mysql_num_rows (mres);
		if (nr != 1) return -2; /* wrong user/pass */

	sqlrow = mysql_fetch_row (mres);

	printf ("cash ###### %s\n", sqlrow[4]);

	sscanf (sqlrow[3],"%c", &me->status);
	sscanf (sqlrow[4],"%lu", &me->cash);

	mysql_free_result (mres);

 return 0;
}

int	db_query (const char* format, ...){

 int err;
 va_list ap;
 char querybuf[1024];

	va_start (ap, format);
	vsnprintf (querybuf, sizeof(querybuf), format, ap);
	va_end (ap);

	err = mysql_query (mysql_con, querybuf);
		if (err != 0){
			db_err ();
			return -1;
		}

 return 0;
}

void db_err(void){

 unsigned int err;

	err = mysql_errno (mysql_con);
	if (err) fprintf (stdout, "%u %s\n", err, mysql_error(mysql_con));
}

void db_cleanup (void){
	mysql_close (mysql_con);
}

int db_connect (const char* host, const char* user, const char* pwd, const char* db, unsigned int port, unsigned int flags){

	mysql_con = mysql_init (NULL);
		if (mysql_con == NULL){
			fprintf (stderr, "couldn't initialize mysql\n");
			return -1;
		}
		else
		{
			mysql_con = mysql_real_connect (mysql_con, host, user, pwd, db, port, NULL, flags);
				if (mysql_con == NULL){
					fprintf (stderr, "unable to connect to mysql\n");
					return -1;
				}
		}

 return 0;
}



